package org.kl.bpm.operation;

import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.task.Task;
import org.kl.bf.utils.ApplicationContextHelper;
import org.kl.bpm.entity.conf.BpmKvRecord;
import org.kl.bpm.service.conf.BpmKvRecordService;

/**
 * 保存草稿.
 */
public class SaveDraftOperation extends AbstractOperation<String> {
	public static final String OPERATION_BUSINESS_KEY = "businessKey";
	public static final String OPERATION_TASK_ID = "taskId";
	public static final String OPERATION_BPM_PROCESS_ID = "bpmProcessId";
	public static final int STATUS_DRAFT_PROCESS = 0;
	public static final int STATUS_DRAFT_TASK = 1;
	public static final int STATUS_RUNNING = 2;

	public String execute(CommandContext commandContext) {
		String taskId = getParameter(OPERATION_TASK_ID);
		String businessKey = getParameter(OPERATION_BUSINESS_KEY);
		String bpmProcessId = getParameter(OPERATION_BPM_PROCESS_ID);
		BpmKvRecordService bpmKvRecordService = getBpmKvRecordService();
		//BpmKvPropService bpmKvPropService = getBpmKvPropService();

		if (this.notEmpty(taskId)) {
			// 如果是任务草稿，直接通过processInstanceId获得record，更新数据
			// TODO: 分支肯定有问题
			Task task = getProcessEngine().getTaskService().createTaskQuery().taskId(taskId).singleResult();

			if (task == null) {
				throw new IllegalStateException("任务不存在");
			}

			String processInstanceId = task.getProcessInstanceId();
			BpmKvRecord record = bpmKvRecordService.findByRef(processInstanceId);

			record = new RecordBuilder().build(record, STATUS_DRAFT_TASK, getParameters());
			bpmKvRecordService.saveBpmKvRecord(record);
			businessKey = record.getId();
		} else if (this.notEmpty(businessKey)) {
			// 如果是流程草稿，直接通过businessKey获得record，更新数据
			BpmKvRecord record = bpmKvRecordService.getBpmKvRecord(businessKey);

			record = new RecordBuilder().build(record, STATUS_DRAFT_PROCESS, getParameters());
			// bpmKvPropService.saveBpmKvProp(record.getBpmKvProps());
			bpmKvRecordService.saveBpmKvRecord(record);
		} else {
			// 如果是第一次保存草稿，肯定是流程草稿，先初始化record，再保存数据
			BpmKvRecord record = new RecordBuilder().build(bpmProcessId, STATUS_DRAFT_PROCESS, getParameters());
			bpmKvRecordService.saveBpmKvRecord(record);
			businessKey = record.getId();
		}

		return businessKey;
	}

	public boolean notEmpty(String str) {
		return (str != null) && (!"".equals(str));
	}

	public BpmKvRecordService getBpmKvRecordService() {
		return ApplicationContextHelper.getBean(BpmKvRecordService.class);
	}

	// public BpmKvPropService getBpmKvPropService() {
	// return ApplicationContextHelper.getBean(BpmKvPropService.class);
	// }
}
